/// <reference path="index.d.ts" />

import React from "react";
import { View } from "@tarojs/components";
import { PickerView } from 'antd-mobile'


type ItemProp = {
    label: string;
    value: any;
}

type StateProp = {
    basicColumns: string[][] | ItemProp[][];
    indexs: number[];
    dataList: any[];

}
type ReducerProp = (state: StateProp, action: Partial<StateProp>) => StateProp

type StyleProp = {
    containerStyle?: React.CSSProperties;
    pickerStyle?: React.CSSProperties;
}
type StyleReducerProp = (state: StyleProp, action: Partial<StyleProp>) => StyleProp


const App = (props: PickerHouseView.Prop, ref) => {

    const [viewModel, setViewModel] = React.useReducer<ReducerProp>(
        (state, action) => ({ ...state, ...action }),
        {
            indexs: [8, 0, 0, 0],
            basicColumns: [],
            dataList: []
        },
    )

    const [styleState, styleDispatch] = React.useReducer<StyleReducerProp>(
        (state, action) => ({ ...state, ...action }),
        {
            containerStyle: styles.container,
            pickerStyle: styles.picker
        })

    React.useImperativeHandle(ref, () => ({
        show: () => {
            show()
        },
        hide: () => {
            hide()
        }
    }), [])


    React.useEffect(() => {

        setViewModel({ dataList: props.dataSource })
        // console.log(props.dataSource)
    }, [props.dataSource])



    const show = () => {
        styleDispatch({
            containerStyle: {
                ...styleState.containerStyle,
                visibility: 'visible',
                transition: 'visibility 0.35s ease-in'
            },
            pickerStyle: {
                ...styleState.pickerStyle,
                transform: `translateY(-${pickerRef?.current?.clientHeight}px)`,
                transition: 'transform 0.35s ease-in'
            }
        })
    }

    const hide = () => {
        styleDispatch({
            containerStyle: {
                ...styleState.containerStyle,
                visibility: 'hidden',
                transition: 'visibility 0.25s ease-out'
            },
            pickerStyle: {
                ...styleState.pickerStyle,
                transform: 'translateY(0px)',
                transition: 'transform 0.25s ease-out'
            }
        })
    }



    React.useEffect(() => {
        let dataList = viewModel.dataList
        if (dataList?.length > 0) {

            let children0 = dataList || []
            let children1: any[] = dataList[viewModel.indexs[0]]?.children || []
            let children2: any[] = children1[viewModel.indexs[1]]?.children || []
            let children3: any[] = children2[viewModel.indexs[2]]?.children || []


            let basicColumns = [
                children0.map(i => i.title),
                children1.map(i => i.title),
                children2.map(i => i.title),
                children3.map(i => i.title)
            ]
            // console.log({ basicColumns })
            setViewModel({ basicColumns })

        }

    }, [viewModel.indexs, viewModel.dataList])



    const findXindex = (val: string[]): number => {
        let length = viewModel.basicColumns?.length
        if (length > 0) {
            let defaultValue: any[] = [viewModel.basicColumns[0][viewModel.indexs[0]]]
            if (length > 1) defaultValue.push(viewModel.basicColumns[1][viewModel.indexs[1]])
            if (length > 2) defaultValue.push(viewModel.basicColumns[2][viewModel.indexs[2]])
            if (length > 3) defaultValue.push(viewModel.basicColumns[3][viewModel.indexs[3]])
            return defaultValue.findIndex((i, idx) => i != val[idx])
        }

        return -1
    }



    const onOk = (e) => {
        // console.log('ok',e)
        try {


            let index = (viewModel.basicColumns as any[][])?.filter(i => i.length).length - 1
            // console.log({index,ds: viewModel.dataList})
            if (index == -1) return
            let item0 = viewModel.dataList[viewModel.indexs[0]]
            let item1 = item0?.children[viewModel.indexs[1]]
            let item2 = item1?.children[viewModel.indexs[2]]
            let item3 = item2?.children[viewModel.indexs[3]]

            // console.log({item0,item1,item2,item3})
            let params: {
                id: number,
                name: string | undefined;
            } = { id: -1, name: undefined }
            if (index == 0) params = {
                id: item0.id,
                name: item0.title
            }
            if (index == 1) params = {
                id: item1.id,
                name: `${item0.title}/${item1.title}`
            }
            if (index == 2) params = {
                id: item2.id,
                name: `${item0.title}/${item1.title}/${item2.title}`
            }
            if (index == 3) params = {
                id: item3.id,
                name: `${item0.title}/${item1.title}/${item2.title}/${item3.title}`
            }

            // console.log(params)
            props.onOk && props.onOk(params)
            hide()
        } catch (error) {
            // console.log(error)
        }

    }



    const pickerRef = React.useRef<any>()

    return (
        <View
            // ref={ref}
            style={styleState.containerStyle} onClick={e => {
                e.stopPropagation()
                hide()
            }}>
            <View style={styleState.pickerStyle} ref={pickerRef} onClick={e => {
                e.stopPropagation();
            }}>
                <View style={styles.header}>
                    <View style={styles.headerLeft} onClick={() => {
                        hide()
                    }}>取消</View>
                    <View style={styles.headerTitle}>详细地址</View>
                    <View style={styles.headerRight} onClick={onOk}>确定</View>
                </View>
                <View style={styles.headerSub}>
                    {
                        ['楼栋', '单元', '楼层', '房号'].map(((item, index) =>
                            <View
                                key={`sg-header-sub-${index}`}
                                style={{ flexGrow: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '13px', color: '#333333' }}
                            >{item}</View>
                        ))
                    }
                </View>
                <PickerView
                    columns={viewModel?.basicColumns}

                    style={{ height: '300px' }}

                    value={(() => {
                        try {
                            return [
                                viewModel.basicColumns[0][viewModel.indexs[0]],
                                viewModel.basicColumns[1][viewModel.indexs[1]],
                                viewModel.basicColumns[2][viewModel.indexs[2]],
                                viewModel.basicColumns[3][viewModel.indexs[3]],
                            ] as any[]
                        } catch (error) {

                        }
                        return []
                    })()}
                    onChange={(val, extend) => {
                        // console.log('onChange', val, extend)
                        let xIndex: number = findXindex(val as string[])
                        // console.log({ xIndex })
                        if (xIndex > -1) {
                            let yValue = val[xIndex] as any
                            let yIndex = viewModel.basicColumns[xIndex].findIndex(i => i == yValue)
                            // console.log({
                            //     yValue,
                            //     yIndex
                            // })

                            let _indexs = [...viewModel.indexs]
                            _indexs[xIndex] = yIndex
                            _indexs = _indexs.map((i, idx) => idx > xIndex ? 0 : i)
                            // console.log({ _indexs })
                            setViewModel({ indexs: _indexs })

                        }

                    }}
                />
            </View>
        </View>

    )
}


// type PickerColumnItem = {
//     label:ReactNode;
//     value:string;
// }
// export const basicColumns = [
//     ['社区综合服务中心', '1栋', '2栋', '3栋', '4栋', '5栋', '6栋', '7栋', '8栋', '9栋', '10栋', '11栋', '12栋', '13栋', '14栋', '15栋', '16栋'],
//     ['物业'],
//     ['0层'],
//     []
//     // ['工程', '客服', '财务', '其他', '安保', '保洁']
// ]




const styles: Record<string, React.CSSProperties> = {
    container: {
        position: 'fixed',
        zIndex: 99999,
        width: '100%',
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: '#00000055',
        visibility: 'hidden',
        overflow: 'hidden'
    },
    picker: {
        position: 'absolute',
        top: '100%',
        width: '100%',
        backgroundColor: 'white'
    },
    header: {
        height: '44px',
        display: 'flex',
    },
    headerLeft: {
        height: '100%',
        width: '25%',
        fontSize: '14px',
        color: '#999999',
        display: 'flex', justifyContent: 'center', alignItems: 'center',
    },
    headerTitle: {
        flexGrow: 1,
        fontSize: '14px',
        color: '#333333',
        display: 'flex', justifyContent: 'center', alignItems: 'center',
    },
    headerRight: {
        height: '100%',
        width: '25%',
        fontSize: '14px',
        color: 'red',
        display: 'flex', justifyContent: 'center', alignItems: 'center',
    },

    headerSub: {
        height: '30px',
        display: 'flex'
    }
}


const HOC = React.forwardRef<PickerHouseView.Current, PickerHouseView.Prop>(App)

export default HOC